<template>
  <a-layout class="database-layout">
    <a-layout-header class="database-header">
      <a-row align="middle" justify="space-between" :wrap="false">
        <a-col flex="auto">
          <a-space direction="vertical" :size="0" style="width: 100%">
            <a-typography-title :level="4" style="margin: 0; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              数据库管理
            </a-typography-title>
            <a-typography-text type="secondary" style="display: block; line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              管理和配置您的数据库连接
            </a-typography-text>
          </a-space>
        </a-col>
        <a-col flex="none" style="margin-left: 16px; display: flex; align-items: center;">
          <a-button type="primary" @click="showCreateConnection = true">
            <template #icon><PlusOutlined /></template>
            添加连接
          </a-button>
        </a-col>
      </a-row>
    </a-layout-header>

    <a-layout-content>
      <a-space direction="vertical" size="middle" style="width: 100%">
        <a-card :hoverable="false" :bordered="false" :bodyStyle="{ padding: '16px' }">
          <a-form layout="inline" :model="searchValues">
            <a-row :gutter="[16, 16]" style="width: 100%">
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="关键词" :colon="false">
                  <a-input
                    v-model:value="searchValues.keyword"
                    placeholder="搜索连接名称或主机地址"
                    allow-clear
                    @change="handleSearch"
                  >
                    <template #prefix>
                      <SearchOutlined />
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="数据库类型" :colon="false">
                  <a-select
                    v-model:value="searchValues.type"
                    placeholder="选择数据库类型"
                    style="width: 100%"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-select-option value="mysql">
                      <a-space>
                        <DatabaseOutlined />
                        MySQL
                      </a-space>
                    </a-select-option>
                    <a-select-option value="postgresql">
                      <a-space>
                        <DatabaseOutlined />
                        PostgreSQL
                      </a-space>
                    </a-select-option>
                    <a-select-option value="sqlserver">
                      <a-space>
                        <DatabaseOutlined />
                        SQL Server
                      </a-space>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item label="状态" :colon="false">
                  <a-select
                    v-model:value="searchValues.status"
                    placeholder="选择状态"
                    style="width: 100%"
                    allow-clear
                    @change="handleSearch"
                  >
                    <a-select-option value="connected">
                      <a-space>
                        <CheckCircleOutlined style="color: #52c41a" />
                        已连接
                      </a-space>
                    </a-select-option>
                    <a-select-option value="disconnected">
                      <a-space>
                        <MinusCircleOutlined style="color: #d9d9d9" />
                        未连接
                      </a-space>
                    </a-select-option>
                    <a-select-option value="error">
                      <a-space>
                        <CloseCircleOutlined style="color: #ff4d4f" />
                        错误
                      </a-space>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xs="24" :sm="12" :md="8" :lg="6">
                <a-form-item :colon="false">
                  <a-space>
                    <a-button type="primary" @click="handleSearch">
                      <template #icon><SearchOutlined /></template>
                      搜索
                    </a-button>
                    <a-button @click="handleReset">
                      <template #icon><ReloadOutlined /></template>
                      重置
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-card>

        <a-card 
          :hoverable="false" 
          :bordered="false"
          :bodyStyle="{ padding: '16px' }"
        >
          <template #extra>
            <a-space>
              <a-tooltip title="刷新数据">
                <a-button type="text" @click="fetchConnections">
                  <template #icon><ReloadOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
          <a-table
            :columns="columns"
            :data-source="connections"
            :loading="loading"
            :pagination="pagination"
            :row-key="record => record.id"
            @change="handleTableChange"
            :scroll="{ x: 'max-content' }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'name'">
                <a-space>
                  <DatabaseOutlined />
                  {{ record.name || '-' }}
                </a-space>
              </template>
              <template v-if="column.key === 'type'">
                <a-tag :color="getTypeColor(record.type)">
                  {{ getTypeText(record.type) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'host'">
                <a-space>
                  <GlobalOutlined />
                  {{ record.host || '-' }}
                </a-space>
              </template>
              <template v-if="column.key === 'port'">
                <a-space>
                  <FieldNumberOutlined />
                  {{ record.port || '-' }}
                </a-space>
              </template>
              <template v-if="column.key === 'database'">
                <a-space>
                  <DatabaseOutlined />
                  {{ record.database || '-' }}
                </a-space>
              </template>
              <template v-if="column.key === 'status'">
                <a-badge
                  :status="getStatusType(record.status || '')"
                  :text="getStatusText(record.status || '')"
                />
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-tooltip title="测试连接">
                    <a-button type="link" @click="handleTest(record)">
                      <template #icon><PlayCircleOutlined /></template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="编辑连接">
                    <a-button type="link" @click="handleEdit(record)">
                      <template #icon><EditOutlined /></template>
                    </a-button>
                  </a-tooltip>
                  <a-tooltip title="删除连接">
                    <a-popconfirm
                      title="确定要删除这个连接吗？"
                      @confirm="handleDelete(record)"
                    >
                      <a-button type="link" danger>
                        <template #icon><DeleteOutlined /></template>
                      </a-button>
                    </a-popconfirm>
                  </a-tooltip>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-space>
    </a-layout-content>

    <a-modal
      v-model:open="showCreateConnection"
      :title="editingConnection ? '编辑连接' : '添加连接'"
      :confirm-loading="submitting"
      @ok="handleSubmit"
      @cancel="showCreateConnection = false"
      width="720px"
      :maskClosable="false"
    >
      <a-form
        :model="connectionForm"
        :rules="connectionRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="连接名称" name="name">
              <a-input 
                v-model:value="connectionForm.name" 
                placeholder="请输入连接名称"
                allow-clear
              >
                <template #prefix>
                  <DatabaseOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="数据库类型" name="type">
              <a-select 
                v-model:value="connectionForm.type" 
                placeholder="请选择数据库类型"
              >
                <a-select-option value="mysql">
                  <a-space>
                    <DatabaseOutlined />
                    MySQL
                  </a-space>
                </a-select-option>
                <a-select-option value="postgresql">
                  <a-space>
                    <DatabaseOutlined />
                    PostgreSQL
                  </a-space>
                </a-select-option>
                <a-select-option value="sqlserver">
                  <a-space>
                    <DatabaseOutlined />
                    SQL Server
                  </a-space>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="主机地址" name="host">
              <a-input 
                v-model:value="connectionForm.host" 
                placeholder="请输入主机地址"
                allow-clear
              >
                <template #prefix>
                  <GlobalOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="端口" name="port">
              <a-input-number 
                v-model:value="connectionForm.port" 
                :min="1" 
                :max="65535" 
                style="width: 100%"
                placeholder="请输入端口号"
              >
                <template #prefix>
                  <FieldNumberOutlined />
                </template>
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="数据库名" name="database">
              <a-input 
                v-model:value="connectionForm.database" 
                placeholder="请输入数据库名"
                allow-clear
              >
                <template #prefix>
                  <DatabaseOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="用户名" name="username">
              <a-input 
                v-model:value="connectionForm.username" 
                placeholder="请输入用户名"
                allow-clear
              >
                <template #prefix>
                  <UserOutlined />
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="密码" name="password">
          <a-input-password 
            v-model:value="connectionForm.password" 
            placeholder="请输入密码"
            allow-clear
          >
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleTestConnection" :loading="testing">
              <template #icon><PlayCircleOutlined /></template>
              测试连接
            </a-button>
            <a-space v-if="testing || testResult" direction="vertical" style="width: 100%">
              <a-space>
                <a-spin v-if="testing" size="small" />
                <a-tag v-else :color="testResult.success ? 'success' : 'error'">
                  {{ testResult.success ? '连接成功' : '连接失败' }}
                </a-tag>
                <span v-if="testResult?.time" class="ant-typography ant-typography-secondary">
                  {{ testResult.time }}ms
                </span>
              </a-space>
              <a-alert
                v-if="testResult && !testResult.success"
                type="error"
                :message="testResult.data"
                show-icon
                banner
              />
            </a-space>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useDatabaseStore } from '../stores/database'
import { useAppStore } from '../stores/app'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  PlayCircleOutlined,
  SearchOutlined,
  ReloadOutlined,
  DatabaseOutlined,
  GlobalOutlined,
  FieldNumberOutlined,
  UserOutlined,
  LockOutlined,
  CheckCircleOutlined,
  MinusCircleOutlined,
  CloseCircleOutlined
} from '@ant-design/icons-vue'

const databaseStore = useDatabaseStore()
const appStore = useAppStore()

const loading = ref(false)
const submitting = ref(false)
const showCreateConnection = ref(false)
const editingConnection = ref(null)
const testResult = ref(null)

const connections = ref([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0
})

const filters = ref({
  type: undefined,
  status: undefined,
  search: ''
})

const connectionForm = ref({
  name: '',
  type: 'mysql',
  host: '',
  port: 3306,
  database: '',
  username: '',
  password: ''
})

const searchValues = ref({
  keyword: '',
  type: undefined,
  status: undefined,
  dateRange: undefined
})

const searchFields = [
  {
    name: 'keyword',
    label: '关键词',
    type: 'input',
    placeholder: '搜索连接名称或主机地址'
  },
  {
    name: 'type',
    label: '数据库类型',
    type: 'select',
    placeholder: '选择数据库类型',
    options: [
      { label: 'MySQL', value: 'mysql' },
      { label: 'PostgreSQL', value: 'postgresql' },
      { label: 'SQL Server', value: 'sqlserver' }
    ]
  },
  {
    name: 'status',
    label: '状态',
    type: 'select',
    placeholder: '选择状态',
    options: [
      { label: '已连接', value: 'connected' },
      { label: '未连接', value: 'disconnected' },
      { label: '错误', value: 'error' }
    ]
  },
  {
    name: 'dateRange',
    label: '创建时间',
    type: 'dateRange',
    placeholder: ['开始日期', '结束日期'],
    advanced: true
  }
]

const columns = [
  {
    title: '连接名称',
    dataIndex: 'name',
    key: 'name',
    sorter: true,
    width: 200
  },
  {
    title: '数据库类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '主机地址',
    dataIndex: 'host',
    key: 'host',
    width: 180
  },
  {
    title: '端口',
    dataIndex: 'port',
    key: 'port',
    width: 100
  },
  {
    title: '数据库名',
    dataIndex: 'database',
    key: 'database',
    width: 150
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right',
    align: 'center'
  }
]

const connectionRules = {
  name: [{ required: true, message: '请输入连接名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择数据库类型', trigger: 'change' }],
  host: [{ required: true, message: '请输入主机地址', trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'change' }],
  database: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: false, message: '请输入密码', trigger: 'blur' }]
}

const getTypeColor = (type) => {
  const colors = {
    mysql: 'blue',
    postgresql: 'green',
    sqlserver: 'orange'
  }
  return colors[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    mysql: 'MySQL',
    postgresql: 'PostgreSQL',
    sqlserver: 'SQL Server'
  }
  return texts[type] || type
}

const getStatusType = (status) => {
  const types = {
    connected: 'success',
    disconnected: 'default',
    error: 'error',
    '': 'default'
  }
  return types[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    connected: '已连接',
    disconnected: '未连接',
    error: '错误',
    '': '未连接'
  }
  return texts[status] || '未连接'
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.value = {
    ...pagination.value,
    current: pag.current,
    pageSize: pag.pageSize
  }
  fetchConnections()
}

const handleSearch = async (values) => {
  Object.assign(searchValues.value, values)
  pagination.value.current = 1 // 重置到第一页
  await fetchConnections()
}

const handleReset = async () => {
  Object.keys(searchValues.value).forEach(key => {
    searchValues.value[key] = undefined
  })
  pagination.value.current = 1 // 重置到第一页
  await fetchConnections()
}

const handleEdit = (record) => {
  editingConnection.value = record
  connectionForm.value = {
    name: record.name,
    type: record.type,
    host: record.host,
    port: record.port,
    database: record.database,
    username: record.username,
    password: ''
  }
  showCreateConnection.value = true
}

const handleDelete = async (record) => {
  try {
    await databaseStore.deleteConnection(record.id)
    appStore.success('删除成功')
    fetchConnections()
  } catch (error) {
    appStore.error('删除失败')
  }
}

const handleTest = async (record) => {
  try {
    const result = await databaseStore.testConnectionDatabase({
      id: record.id,
      type: record.type,
      host: record.host,
      port: record.port,
      database: record.database,
      username: record.username,
      password: record.password
    })
    appStore.success(`连接测试成功 (${result.time}ms)`)
  } catch (error) {
    appStore.error(`连接测试失败: ${error.message}`)
  }
}

const handleSubmit = async () => {
  submitting.value = true
  try {
    const formData = { ...connectionForm.value }
    // 如果是编辑模式且密码为空，则不提交密码字段
    if (editingConnection.value && !formData.password) {
      delete formData.password
    }

    if (editingConnection.value) {
      await databaseStore.updateConnection(editingConnection.value.id, formData)
      appStore.success('更新成功')
    } else {
      const response = await databaseStore.createConnection(formData)
      if (response && response.code === 200) {
        appStore.success('创建成功')
        showCreateConnection.value = false
        await fetchConnections()
      } else {
        throw new Error(response?.message || '创建失败')
      }
    }
  } catch (error) {
    appStore.error(error.message || (editingConnection.value ? '更新失败' : '创建失败'))
  } finally {
    submitting.value = false
    editingConnection.value = null
    connectionForm.value = {
      name: '',
      type: 'mysql',
      host: '',
      port: 3306,
      database: '',
      username: '',
      password: ''
    }
  }
}

const testing = ref(false)

const handleTestConnection = async () => {
  testing.value = true
  testResult.value = null
  try {
    const formData = { ...connectionForm.value }
    // 如果是编辑模式且密码为空，则不提交密码字段
    if (editingConnection.value && !formData.password) {
      delete formData.password
    }
    const result = await databaseStore.testConnectionDatabase(formData)
    testResult.value = {
      success: true,
      time: result.time,
      data: result.data
    }
    appStore.success(`连接测试成功 (${result.time}ms)`)
  } catch (error) {
    testResult.value = {
      success: false,
      time: 0,
      data: error.message
    }
    appStore.error(`连接测试失败: ${error.message}`)
  } finally {
    testing.value = false
  }
}

const fetchConnections = async () => {
  loading.value = true
  try {
    const { data, total } = await databaseStore.fetchConnections({
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      type: searchValues.value.type,
      status: searchValues.value.status,
      keyword: searchValues.value.keyword
    })
    connections.value = Array.isArray(data) ? data : []
    pagination.value.total = total || 0
  } catch (error) {
    if (error.response?.status !== 404) {
      appStore.error('获取连接列表失败')
    }
    connections.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 监听弹窗显示状态
watch(showCreateConnection, (newVal) => {
  if (!newVal) {
    // 关闭弹窗时重置表单和测试结果
    connectionForm.value = {
      name: '',
      type: 'mysql',
      host: '',
      port: 3306,
      database: '',
      username: '',
      password: ''
    }
    testResult.value = null
    editingConnection.value = null
    testing.value = false
  }
})

// 监听分页参数变化
watch(
  () => [pagination.value.current, pagination.value.pageSize],
  () => {
    fetchConnections()
  }
)

onMounted(() => {
  fetchConnections()
})
</script>

<style scoped>
.database-layout {
  min-height: 100vh;
}

.database-header {
  background: #fff;
  padding: 12px 24px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  position: sticky;
  top: 0;
  z-index: 1;
  height: auto;
  line-height: normal;
}

:deep(.ant-layout-content) {
  padding: 24px;
  background: #f0f2f5;
}

:deep(.ant-form-item-label) {
  padding-bottom: 4px;
}

:deep(.ant-form-item-label > label) {
  height: 24px;
  line-height: 24px;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

/* 暗色主题适配 */
[data-theme='dark'] {
  .database-header {
    background: #1f1f1f;
  }

  :deep(.ant-layout-content) {
    background: #141414;
  }

  :deep(.ant-table-thead > tr > th) {
    background: #1f1f1f;
  }
}

/* 响应式布局 */
@media (max-width: 768px) {
  .database-header {
    padding: 12px 16px;
  }

  :deep(.ant-layout-content) {
    padding: 16px;
  }

  :deep(.ant-form-item) {
    margin-bottom: 16px;
  }

  :deep(.ant-card-body) {
    padding: 12px !important;
  }
}
</style> 